/**
 * 图片头数据加载就绪事件 - 更快获取图片尺寸
 * @version	2011.05.27
 * @author	TangBin
 * @see		http://www.planeart.cn/?p=1121
 * @param	{String}	图片路径
 * @param	{Function}	尺寸就绪
 * @param	{Function}	加载完毕 (可选)
 * @param	{Function}	加载错误 (可选)
 * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () {
		//this.width,this.height
	});
 */
var imgReady = (function () {
	var list = [], intervalId = null,

	// 用来执行队列
	tick = function () {
		var i = 0;
		for (; i < list.length; i++) {
			list[i].end ? list.splice(i--, 1) : list[i]();
		};
		!list.length && stop();
	},

	// 停止所有定时器队列
	stop = function () {
		clearInterval(intervalId);
		intervalId = null;
	};

	return function (url, ready, load, error) {
		var onready, width, height, newWidth, newHeight,
			img = new Image();
		
		img.src = url;

		// 如果图片被缓存，则直接返回缓存数据
		if (img.complete) {
			ready.call(img);
			load && load.call(img);
			return;
		};
		
		width = img.width;
		height = img.height;
		
		// 加载错误后的事件
		img.onerror = function () {
			error && error.call(img);
			onready.end = true;
			img = img.onload = img.onerror = null;
		};
		
		// 图片尺寸就绪
		onready = function () {
			newWidth = img.width;
			newHeight = img.height;
			if (newWidth !== width || newHeight !== height ||
				// 如果图片已经在其他地方加载可使用面积检测
				newWidth * newHeight > 1024
			) {
				ready.call(img);
				onready.end = true;
			};
		};
		onready();
		
		// 完全加载完毕的事件
		img.onload = function () {
			// onload在定时器时间差范围内可能比onready快
			// 这里进行检查并保证onready优先执行
			!onready.end && onready();
		
			load && load.call(img);
			
			// IE gif动画会循环执行onload，置空onload即可
			img = img.onload = img.onerror = null;
		};

		// 加入队列中定期执行
		if (!onready.end) {
			list.push(onready);
			// 无论何时只允许出现一个定时器，减少浏览器性能损耗
			if (intervalId === null) intervalId = setInterval(tick, 40);
		};
	};
})();
//扩展
(function($){
	//私有方法
	var dopic = function(options,pic) {
		var settings = {
			next: '.next',  
			prev: '.prev',
			picbox:'#picbox',
			curr:'curr',
			maxwidth:800,
			maxheight:0,
			autoplay:false,
			speed:500,
			opacity:0.5,
			disnum:0//不兼容设置可见列表数
			};
		settings = $.extend(settings,options);

		var piclist = $(picbox).children().first();
		//图片载入处理
		var loadimg = function(img){
			var litpic = img.attr('src');
			var src = img.attr('datasrc') ? img.attr('datasrc') : litpic;
		
			piclist.find('img.'+settings.curr).removeClass(settings.curr);//移动旧的选中
			img.addClass(settings.curr);//设置新的选中
						
			imgReady(src, function () {
				var height=this.height,width=this.width;
				if(width>settings.maxwidth){
					height = parseInt(settings.maxwidth*height/width);
					width = settings.maxwidth;
				}
				$(pic).html('<img id="gallery_y_litimg" src="'+ litpic +'" width="'+ width +'" height="'+ height +'" style="width:'+width+'px;height:'+height+'px;position:absolute;left:50%;top:50%;margin-left:-'+ parseInt(width/2) +'px;margin-top:-'+ parseInt(height/2) +'px;background:transparent;" />');
				var pic_height = $(pic).height();
				$(pic).css({'position':'relative'});
				if(height>settings.maxheight) pic_height = height;
				$(pic).css({'height':pic_height+'px'});//重置图片框高度

				$('#gallery_y_big').remove();
				// 插入大图并使用逐渐清晰加载的效果
				$('#gallery_y_litimg').after('<img id="gallery_y_big" src="'+ src +'" style="width:'+width+'px;height:'+height+'px;position:absolute;left:50%;top:50%;margin-left:-'+ parseInt(width/2) +'px;margin-top:-'+ parseInt(height/2) +'px;background:transparent;" />');
			}, function(){//大图加载完毕
				$('#gallery_y_litimg').hide();
			});
		}
		
		var first = piclist.find('img').first();
		loadimg(first);
		piclist.find('img').each(function(){
			$(this).css("cursor","pointer");
			$(this).click(function(){
				loadimg($(this));
			});
		});
		var li_height = piclist.children().first().outerHeight(true);//单项高度
		var li_num = piclist.children().length;//列表数
		var dis_li_num = settings.disnum;//可见列表数
		if(dis_li_num==0){
			dis_li_num = $(picbox).height()/li_height;
			dis_li_num = Math.round(dis_li_num)>= dis_li_num ? Math.round(dis_li_num) : Math.round(dis_li_num)+1;
		}
		var page = piclist.height()/$(picbox).height();//页数
		if(dis_li_num>=li_num) page=1;
		else page = Math.round(page)>= page ? Math.round(page) : Math.round(page)+1;
		var upHeight=dis_li_num*li_height;//翻动高度$(picbox).height();//
		
		//alert($(picbox).height()+'--'+piclist.height()+'--'+page+'=='+dis_li_num+'==='+li_height+'=='+li_num);
		
		var _btnUp = $(settings.prev);//Shawphy:向上按钮
		var _btnDown = $(settings.next);//Shawphy:向下按钮
		var curr_page=0;
		var speed=settings.speed; //卷动速度，数值越大，速度越慢（毫秒）
		//透明
		var opacity=function(o,op){
			if(op) o.css({'cursor': 'default','opacity': settings.opacity,'filter': 'Alpha(opacity='+ settings.opacity*100 +')'});
			else o.css({'cursor': 'pointer','opacity': '1','filter': 'Alpha(opacity=100)'});
		}
		var chang_opacity=function(){
			if(curr_page<=0) opacity(_btnUp,true);else opacity(_btnUp);
			if(curr_page>=page-1) opacity(_btnDown,true);else opacity(_btnDown);
			//alert(curr_page+'=='+page);
		}
		var scrollUp=function(){//上翻
			curr_page--;chang_opacity();
			if(curr_page<0) {curr_page=0;chang_opacity();return;}//
			_btnUp.unbind("click",scrollUp); //Shawphy:取消向上按钮的函数绑定
			piclist.animate({'margin-top': '-'+ curr_page*upHeight +'px'},speed,function(){
				_btnUp.bind("click",scrollUp); //Shawphy:绑定向上按钮的点击事件
				//alert(curr_page);
			});
		}
		var scrollDown=function(){//下翻
			curr_page++;chang_opacity();
			if(curr_page>=page) {curr_page=page-1;chang_opacity();return;}// 
			_btnDown.unbind("click",scrollDown);
			piclist.animate({'margin-top': '-'+ curr_page*upHeight +'px'},speed,function(){
				_btnDown.bind("click",scrollDown);
				//alert(curr_page);
			});
		}
		//鼠标事件绑定
		_btnUp.click( scrollUp );//Shawphy:向上向下鼠标事件绑定
		_btnDown.click( scrollDown );
		chang_opacity();
	};
	//公开的
	$.fn.gallery_y = function(options) { 
		var pic = $(this);
		dopic(options,pic);
	}
})(jQuery);